package cc.chinagps.gboss;

import cc.chinagps.gateway.buff.DeliverBuff;
import cc.chinagps.gateway.buff.GBossDataBuff;
import cc.chinagps.gboss.bean.Gps;
import cc.chinagps.gboss.common.Config;
import cc.chinagps.gboss.common.util.HttpClientPoolUtil;
import cc.chinagps.gboss.mq.cache.DataCache;
import cc.chinagps.gboss.mq.cache.ICache;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class GpsManager {
    private GpsManager() {

    }

    private static class SingletonHolder {
        private static final GpsManager INSTANCE = new GpsManager();
    }

    public static final GpsManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private ICache<DeliverBuff.DeliverGPS> gpsCache = new DataCache<>("gpsCache", Config.SYS.GPS_FILES_MAX_CACHE_SIZE);

    public void init() {
        new GpsSender().start();
    }

    public boolean addGpsList(List<DeliverBuff.DeliverGPS> list) {
        if (list != null && list.size() > 0) {
            return gpsCache.addDataList(list);
        }
        return false;
    }

    class GpsSender extends Thread {
        public void run() {
            while (true) {
                try {
                    List<DeliverBuff.DeliverGPS> data = gpsCache.getData();
                    if (data != null && data.size() > 0) {
                        List<Gps> list = new ArrayList<>();
                        for (DeliverBuff.DeliverGPS deliverGPS : data) {
                            GBossDataBuff.GpsInfo gpsInfo = deliverGPS.getGpsinfo();
                            GBossDataBuff.GpsBaseInfo baseInfo = gpsInfo.getBaseInfo();
                            Gps gps = new Gps();
                            gps.setTerminalId(gpsInfo.getCallLetter());
                            gps.setAltitude(baseInfo.getHeight());
                            gps.setLatitude(Double.valueOf(baseInfo.getLat()) / 1000000);
                            gps.setLongitude(Double.valueOf(baseInfo.getLng()) / 1000000);
                            gps.setBearing(baseInfo.getCourse());
                            gps.setSpeed(baseInfo.getSpeed() + "");
                            gps.setSendTime(baseInfo.getGpsTime() + "");
                            gps.setState("");
                            list.add(gps);
                        }
                        String s = HttpClientPoolUtil.doPost(Config.SYS.GPS_SEND_URL, ContentType.APPLICATION_JSON.toString(), JSONObject.toJSONString(list));
                        log.debug("send gps result:{}", s);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }
}
